import { prisma } from '@src/common/database'

export type LiveTrialState = {
  roomId: string
  ended: boolean
  totalSec?: number
  createdAt?: string
  endedAt?: string
}

const TRIAL_KEY_PREFIX = 'live.trial.user.'

export async function getLiveTrialState(userId: bigint): Promise<LiveTrialState | null> {
  const key = TRIAL_KEY_PREFIX + String(userId)
  const rec = await prisma.appSetting.findUnique({ where: { key } })
  if (!rec?.value) return null
  const v = rec.value as any
  return {
    roomId: String(v?.roomId ?? ''),
    ended: Boolean(v?.ended ?? false),
    totalSec: v?.totalSec != null ? Number(v.totalSec) : undefined,
    createdAt: v?.createdAt ? String(v.createdAt) : undefined,
    endedAt: v?.endedAt ? String(v.endedAt) : undefined,
  }
}

export async function setLiveTrialState(userId: bigint, state: LiveTrialState): Promise<void> {
  const key = TRIAL_KEY_PREFIX + String(userId)
  await prisma.appSetting.upsert({
    where: { key },
    create: { key, value: state as any },
    update: { value: state as any },
  })
}

export async function clearLiveTrialState(userId: bigint): Promise<void> {
  const key = TRIAL_KEY_PREFIX + String(userId)
  try {
    await prisma.appSetting.delete({ where: { key } })
  } catch {
    // ignore
  }
}

